package com.siblings.loan.ui.steps.impl

import android.content.Context
import com.lib.base.utils.log.LogHelper
import com.siblings.http.callback.StringCallback
import com.siblings.http.model.Progress
import com.siblings.http.model.Response
import com.siblings.http.request.base.Request
import com.siblings.loan.config.SibConfigs
import com.siblings.loan.http.ApiService
import com.siblings.loan.http.ApiService.addCommonParams
import com.siblings.loan.http.HttpHelper
import com.siblings.loan.http.IHttpCallback
import com.siblings.loan.ui.steps.view.ISibStepsView
import com.siblings.loan.utils.StringDeepCopy
import com.siblings.loan.utils.helper.SharedHelper
import com.siblings.mvp.presenter.MvpPresenter
import org.json.JSONArray
import org.json.JSONObject

/**
 * Siblings
 * @Author wwdeng
 * @CreateTime: 2024/7/4 15:46
 * @Annotation：认证流程列表 Presenter 实现
 */
class SibStepsPresenterImpl(context: Context?) : MvpPresenter<ISibStepsView>(context) {

    //流程步骤数据
    private var stepData: JSONObject? = null

    /**
     * 获取全部流程
     */
    fun loadSibProcessStepAction(){
        stepData = JSONObject(SharedHelper.getSibSPString(SharedHelper.SIB_SPKEY.SIBLINGS_PROCESS))
        val allStepTitles = stepData!!.optJSONArray("allStepTitles")
        val stepList = arrayListOf<JSONObject>()
        //当前进行的步骤
        val curtIndex = getStepIndex()
        for (i in 0 until allStepTitles!!.length()) {
            val stepObj = JSONObject()
            stepObj.put("stepTitle", allStepTitles.optString(i))
            stepObj.put("selectIndex", curtIndex)
            stepObj.put("itemCount", allStepTitles.length())
            stepList.add(stepObj)
        }
        //设置所有步骤列表
        showSibStepPage(stepList)
    }

    /**
     * 上传图片
     */
    fun onSibUploadImageAction(imgPath: String){
        val httpUrl = ApiService.getHttpUrl(ApiService.API_URL.SIB_API_UPLOAD_FILE_URL)
        HttpHelper.uploadSibFileAction(httpUrl,imgPath,object : StringCallback(){
            override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>?) {
                super.onStart(request)
                LogHelper.e("upload start")
            }
            override fun onSuccess(response: Response<String>?) {
                LogHelper.e("upload success ："+response!!.body())
                if (response.code() == 200){
                    val data = JSONObject(response!!.body())
                    when(data.optInt("code")){
                        0 -> {//成功
                            val imgUrl = data.optJSONObject("obj")!!.optString("url")
                            mvpView.showSibUploadImageSuccess(imgPath,imgUrl)
                        }
                        else -> {
                            val msg = data.optString("msg")
                            mvpView.showSibToast(msg)
                        }
                    }
                } else {
                    mvpView.showSibToast(response.message())
                }
            }
            override fun onError(response: Response<String>?) {
                LogHelper.e("upload error： "+response!!.body())
                mvpView.showSibToast(response.message())
            }
            override fun uploadProgress(progress: Progress) {
                LogHelper.e("uploadProgress: $progress")
                LogHelper.e("uploadProgress，total: ${progress.totalSize}")
                LogHelper.e("uploadProgress，progress: ${progress.currentSize}")
            }
            override fun onFinish() {
                mvpView.hideSibLoading()
            }
        })
    }

    /**
     * 获取已绑定的账户列表
     */
    fun loadSibAccountListAction() {
        mvpView.showSibLoading()
        val httpUrl = ApiService.getHttpUrl(ApiService.API_URL.SIB_API_COMMON_URL)
        val params = JSONObject().addCommonParams().apply {
            put("path", ApiService.API_PATH.SIB_API_ACCOUNT_LIST_FRENCH_PATH)
        }
        HttpHelper.postSibAction(httpUrl, params, object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        val array = data.optJSONArray("obj")
                        val accountList = arrayListOf<JSONObject>()

                        if (array != null && array.length() > 0) {
                            for (i in 0..<array.length()) {
                                val item = array.optJSONObject(i)
                                item.put("isEdit", false)
                                accountList.add(item)
                            }
                        }

                        if (accountList.size < 2) {
                            for (i in 0..<2 - accountList.size) {
                                val item = JSONObject()
                                item.put("isEdit", true)
                                accountList.add(item)
                            }
                        }
                        mvpView.showSibAccountList(accountList)
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView!!.showSibToast(msg)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView.showSibToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                mvpView.hideSibLoading()
            }
        })
    }

    /**
     * 添加绑卡
     */
    fun submitSibBindAccountAction(mobile: String, walletChannel: String, bindFlag:String = "NO"){
        mvpView.showSibLoading()
        val httpUrl = ApiService.getHttpUrl(ApiService.API_URL.SIB_API_COMMON_URL)
        val params = JSONObject().addCommonParams().apply {
            put("path", ApiService.API_PATH.SIB_API_ACCOUNT_ADD_PATH)
            put("walletMobile", mobile)
            put("walletMobileConfirm", mobile)
            put("walletChannel", walletChannel)
            put("addBindFlag", bindFlag)
        }
        HttpHelper.postSibAction(httpUrl, params, object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                //刷新列表
                loadSibAccountListAction()
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj") ?: JSONObject()

                        // "YES/NO 是否需要提示用户这个号码可以绑另一个渠道的钱包"
                        val addBindFlag = obj.optString("addBindFlag")
                        if (addBindFlag == "YES") {
                            //需要提示绑定另一个渠道账户
                            var otherAccountInfo: JSONObject? = null

                            //用于从APP配置中获取（walletChannels）对应的信息
                            val channel = obj.optString("channel")
                            if (channel.isNotBlank()) {
                                val spData = SharedHelper.getSibSPString(SharedHelper.SIB_SPKEY.SIBLINGS_COMMON)
                                val commonData = JSONObject(spData)
                                val customize = commonData.optJSONObject("customize")
                                if (customize != null) {
                                    val walletChannels = customize.optJSONArray("walletChannels")
                                    if (walletChannels != null && walletChannels.length() > 0) {
                                        for (i in 0..<walletChannels.length()) {
                                            val item = walletChannels.optJSONObject(i)
                                            if (channel == item.optString("value")) {
                                                otherAccountInfo = item
                                                break
                                            }
                                        }
                                    }

                                    // 只有非空的情况下才处理
                                    if (otherAccountInfo != null) {
                                        otherAccountInfo.put("walletMobile", mobile)
                                        //提示绑定另一个渠道账户
                                        mvpView.showSibBingAccountOtherDialog(otherAccountInfo)
                                        return
                                    }
                                }
                            }
                        }
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView!!.showSibToast(msg)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView.showSibToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                mvpView.hideSibLoading()
            }
        })
    }

    /**
     * 删除账户
     */
    fun deleteSibAccountAction(ids: String) {
        mvpView.showSibLoading()
        val httpUrl = ApiService.getHttpUrl(ApiService.API_URL.SIB_API_COMMON_URL)
        val params = JSONObject().addCommonParams().apply {
            put("path", ApiService.API_PATH.SIB_API_ACCOUNT_DELETE_PATH)
            put("ids", ids)
        }
        HttpHelper.postSibAction(httpUrl, params, object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                mvpView.showSibToast(data.optString("msg"))
                when(data.optInt("code")) {
                    0 -> {//成功
                        //刷新列表
                        loadSibAccountListAction()
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView!!.showSibToast(msg)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView.showSibToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                mvpView.hideSibLoading()
            }
        })
    }

    /**
     * 提交数据
     */
    fun onSibSubmitProcessAction(params: JSONObject){
        mvpView.showSibLoading()
        val httpUrl = ApiService.getHttpUrl(ApiService.API_URL.SIB_API_PROCESS_URL)
        HttpHelper.postSibAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        mvpView.showSibSubmitSuccess()
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView!!.showSibToast(msg)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView.showSibToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                mvpView.hideSibLoading()
            }
        })
    }

    /**
     * 根据Step类型显示不同的Page
     */
    private fun showSibStepPage(stepList: ArrayList<JSONObject>){
        //当前进行的步骤
        var curtIndex = getStepIndex()
        if (curtIndex == -1){//已完成
            curtIndex = stepList.size
        }

        //移除所有的流程步骤
        mvpView.removeSibStepAllViews()
        for (i in 0..<stepList.size){
            val stepItem = stepList[i]
            if (i < curtIndex){//已完成
                mvpView.addSibStepAfterView(stepItem)
            } else if (i == curtIndex){//正在进行
                mvpView.addSibStepCurrentView(stepItem)
            } else {//未开始
                mvpView.addSibStepBeforeView(stepItem)
            }
        }

        val allSteps = stepData!!.optJSONArray("allSteps")
        if (curtIndex == stepList.size){//所有步骤已完成
            mvpView.showSibLoanAppalyPage()
            return
        }
        //获取对应的key
        val curtKey = allSteps?.optString(curtIndex)
        //Contact 类型
        if (stepData!!.has(curtKey)){
            val stepData = stepData!!.optJSONObject(curtKey)
            stepData?.put("stepTitle",curtKey)
            if (stepData != null && stepData.has("isContact") && stepData.optString("isContact") == "YES"){
                setSibContactListData(stepData)
                return
            }
        }

        //todo Ocr证件照样式
        if (curtKey!!.contains("ocr_info")){
            mvpView.showSibStepOcrPage()
            return
        }

        //todo Selfie自拍照样式
        if (curtKey.contains("sefie_info")){
            mvpView.showSibStepSelfiePage()
            return
        }

        //todo Account账户样式（法语地区绑定账号）
        if (curtKey.contains("account_info") && SibConfigs.isFrench()){
            mvpView.showSibStepAccountPage()
            return
        }
        //常规通用样式
        if (stepData!!.has(curtKey)){
            val stepData = stepData!!.optJSONObject(curtKey)
            if (stepData != null) {
                stepData.put("stepTitle",curtKey)
                setSibCommonListData(stepData)
            }
        }
    }

    /**
     * 设置通用列表
     */
    private fun setSibCommonListData(data: JSONObject){
        val dataList = arrayListOf<JSONObject>()
        val dataArray = data.optJSONArray("dataList")
        if (dataArray != null) {
            for (i in 0..<dataArray.length()){
                dataList.add(dataArray.optJSONObject(i))
            }
        }

        mvpView.showSibStepCommonPage(data,dataList)
    }

    /**
     * 设置联系人列表
     */
    private fun setSibContactListData(data: JSONObject){
        // TODO: 这里dataList需要深拷贝，否则列表会共用一个数据源
        val stringCopy = StringDeepCopy(data.optString("dataList"))
        val dataList = arrayListOf<JSONObject>()
        for (i in 0..<data.optInt("itemCount")){
            val obj = JSONObject()
            val dataArray = JSONArray(stringCopy.content)
            for (j in 0..<dataArray.length()){
                val dataObj = dataArray.optJSONObject(j)
                dataObj.put("title",dataObj.optString("title"))
                when(dataObj.optString("action")){
                    "CONTACT_GROUP_RELATION",
                    "SELECT" -> {
                        dataObj.put("action","SELECT")
                        val valueArray = data.optJSONArray("relationShips").optJSONArray(i)
                        val values = JSONArray()
                        for (n in 0..<valueArray.length()){
                            val value = JSONObject()
                            value.put("title",valueArray.optString(n))
                            value.put("value",valueArray.optString(n))
                            values.put(value)
                        }
                        dataObj.put("values",values)
                    }
                    else -> {
                        dataObj.put("action","INPUT")
                    }
                }
            }
            obj.put("dataList",dataArray)
            dataList.add(obj)
        }
        mvpView.showSibStepContactPage(data,dataList)
    }

    /**
     * 获取 steps 中第一个在步骤在总步骤中是第几个
     */
    private fun getStepIndex(): Int{
        var index = -1
        //剩余未完成步骤
        val steps = stepData!!.optJSONArray("steps")
        if (steps == null || steps.length() == 0){//已完成
            return index
        }
        //总步骤
        val allSteps = stepData!!.optJSONArray("allSteps") ?: return index

        //当前进行的步骤
        val curtStep = steps.optString(0)
        for (i in 0..<allSteps.length()){
            if (curtStep == allSteps.optString(i)){
                index = i
                break
            }
        }
        return index
    }
}